package com.hanxiaozhang.threadbase2ndedition.no6cacheline;

import java.util.concurrent.CountDownLatch;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用缓存对齐〉
 *  注释 private long p1, p2, p3, p4, p5, p6, p7
 *      private long p9, p10, p11, p13, p14, p15 速度会慢
 *  原因：使用缓存对齐 -> CacheLine占64B long占4B 需要16个long可以填满一行CacheLine
 *  另一种写法使用@Contended  https://blog.csdn.net/hxg117/article/details/78064632
 *
 *
 *
 * @author hanxinghua
 * @create 2021/11/4
 * @since 1.0.0
 */
public class No1CacheLinePadding {


    public static long COUNT = 10_0000_0000L;

    private static class T {
        private long p1, p2, p3, p4, p5, p6, p7;
        public long x = 0L;
        private long p9, p10, p11, p13, p14, p15;
    }

    public static T[] arr = new T[2];

    static {
        arr[0] = new T();
        arr[1] = new T();
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(2);
        Thread t1 = new Thread(() -> {
            for (long i = 0; i < COUNT; i++) {
                arr[0].x = i;
            }
            latch.countDown();
        });
        Thread t2 = new Thread(() -> {
            for (long i = 0; i < COUNT; i++) {
                arr[1].x = i;
            }
            latch.countDown();
        });
        final long startTime = System.nanoTime();
        t1.start();
        t2.start();
        latch.await();
        System.out.println((System.nanoTime() - startTime) / 100_1000);

    }

}
